#include "qimsgsync.h"

const uint8_t QiMSGSync::cmd_reboot[2]={Code::REBOOT, Code::EOC};
const uint8_t QiMSGSync::cmd_sync[2]={Code::GET_SYNC, Code::EOC};
const uint8_t QiMSGSync::cmd_stream[2]={Code::STREAM, Code::EOC};

//QiMSGSync::QiMSGSync(QObject *parent) : QObject(parent)
//{

//}

int QiMSGSync::__getSync()
{
    //qDebug("Sync[%3d]: %02X %02X %02X %02X %02X %02X", recv_len, recv_data[0], recv_data[1], recv_data[2], recv_data[3], recv_data[4], recv_data[5]);
    uint8_t c = __recv();
    if(static_cast<uint8_t>(Code::INSYNC) != c)
    //if (c != (uint8_t)Code::INSYNC)
    {
        qDebug("unexpected {%0X} instead of INSYNC", c);
        return -1;
    }
    c = __recv();
    //if (c == (uint8_t)Code::INVALID)
    if(static_cast<uint8_t>(Code::INVALID) == c)
    {
        qDebug("bootloader reports INVALID OPERATION:%0X", c);
        return -1;
    }
    //if (c == (uint8_t)Code::FAILED)
    if(static_cast<uint8_t>(Code::FAILED) == c)
    {
        qDebug("bootloader reports OPERATION FAILED:%0X", c);
        return -1;
    }
    //if (c != (uint8_t)Code::OK)
    if(static_cast<uint8_t>(Code::OK) != c)
    {
        qDebug("unexpected {%0X} instead of OK", c);
        return -1;
    }
    return 0;
}

int QiMSGSync::__recv_int()
{
#if 0
    uint8_t raw[4];
    memset(raw, 0, sizeof(raw));
    __recv(raw, 4);
    int val = (raw[0]&0xFF) | (raw[1]&0xFF<<8) | (raw[2]&0xFF<<16) | (raw[3]&0xFF<<24);
    return val;
#else
    uint8_t raw[4];
    memset(raw, 0, sizeof(raw));
    __recv(raw, 4);
    //int val = (raw[0]&0xFF) | (raw[1]&0xFF<<8) | (raw[2]&0xFF<<16) | (raw[3]&0xFF<<24);
    uint32_t val=0;
    val = raw[3]&0xFF;
    val <<= 8; val |= raw[2]&0xFF;
    val <<= 8; val |= raw[1]&0xFF;
    val <<= 8; val |= raw[0]&0xFF;
    //val = (val<<8) | raw[2]&0xFF;
//    val = (val<<8) | raw[1]&0xFF;
//    val = (val<<8) | raw[0]&0xFF;
    //return (int)val;
    return  static_cast<int>(val);
#endif
}
